"use client";

import { useState } from "react";
import AudioUploader from "@/components/AudioUploader";
import EmotionResult from "@/components/EmotionResult";
import SystemStatus from "@/components/SystemStatus";
import ModelManager from "@/components/ModelManager";

/**
 * 语音情感识别系统主页组件
 * 功能：整合音频上传、情感分析结果展示、系统状态监控和模型管理
 * 使用场景：用户操作的主界面
 */
export default function Home() {
  // 当前标签页
  const [activeTab, setActiveTab] = useState<"predict" | "models">("predict");
  
  // 预测结果状态
  const [predictionResult, setPredictionResult] = useState<{
    predicted_emotion: string;
    confidence: number;
    probabilities: Record<string, number>;
    processing_time: number;
    filename: string;
  } | null>(null);
  // 加载状态
  const [isLoading, setIsLoading] = useState(false);
  // 错误状态
  const [error, setError] = useState<string | null>(null);

  /**
   * 处理音频上传和预测
   * 参数：file - 上传的音频文件
   */
  const handleAudioUpload = async (file: File) => {
    setIsLoading(true);
    setError(null);
    setPredictionResult(null);

    try {
      const formData = new FormData();
      formData.append("audio_file", file);

      const response = await fetch("/api/predict", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.detail || `预测失败: ${response.status} ${response.statusText}`);
      }

      const result = await response.json();
      setPredictionResult(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "预测过程中发生未知错误");
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 重置界面状态
   */
  const handleReset = () => {
    setPredictionResult(null);
    setError(null);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 dark:from-slate-900 dark:to-slate-800">
      {/* 页面头部 */}
      <header className="bg-white dark:bg-slate-800 shadow-sm border-b border-gray-200 dark:border-slate-700">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-6">
            <div className="flex items-center space-x-3">
              <div className="text-3xl">🎙️</div>
              <div>
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                  语音情感识别系统
                </h1>
                <p className="text-sm text-gray-600 dark:text-gray-300">
                  基于传统算法的语音感情色彩提炼
                </p>
              </div>
            </div>
            <SystemStatus />
          </div>
          
          {/* 导航标签 */}
          <div className="border-t border-gray-200 dark:border-slate-700">
            <nav className="flex space-x-8" aria-label="Tabs">
              <button
                onClick={() => setActiveTab("predict")}
                className={`py-2 px-1 border-b-2 font-medium text-sm ${
                  activeTab === "predict"
                    ? "border-blue-500 text-blue-600 dark:text-blue-400"
                    : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300"
                }`}
              >
                情感识别
              </button>
              <button
                onClick={() => setActiveTab("models")}
                className={`py-2 px-1 border-b-2 font-medium text-sm ${
                  activeTab === "models"
                    ? "border-blue-500 text-blue-600 dark:text-blue-400"
                    : "border-transparent text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 hover:border-gray-300"
                }`}
              >
                模型管理
              </button>
            </nav>
          </div>
        </div>
      </header>

      {/* 主要内容区域 */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {activeTab === "predict" ? (
          // 情感识别标签页
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
            {/* 左侧：音频上传区域 */}
            <div className="space-y-6">
              <div className="bg-white dark:bg-slate-800 rounded-lg shadow-lg p-6">
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                  音频文件上传
                </h2>
                <AudioUploader
                  onUpload={handleAudioUpload}
                  isLoading={isLoading}
                  onReset={handleReset}
                />
              </div>

              {/* 系统说明 */}
              <div className="bg-white dark:bg-slate-800 rounded-lg shadow-lg p-6">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">
                  系统特性
                </h3>
                <ul className="space-y-2 text-sm text-gray-600 dark:text-gray-300">
                  <li className="flex items-center space-x-2">
                    <span className="text-green-500">✓</span>
                    <span>支持WAV、MP3、FLAC等主流音频格式</span>
                  </li>
                  <li className="flex items-center space-x-2">
                    <span className="text-green-500">✓</span>
                    <span>基于MFCC、ZCR、Chroma等传统特征</span>
                  </li>
                  <li className="flex items-center space-x-2">
                    <span className="text-green-500">✓</span>
                    <span>支持中性、平静、快乐、悲伤、愤怒、恐惧、厌恶、惊讶八种情感识别</span>
                  </li>
                  <li className="flex items-center space-x-2">
                    <span className="text-green-500">✓</span>
                    <span>可解释性强，资源需求低</span>
                  </li>
                </ul>
              </div>
            </div>

            {/* 右侧：结果展示区域 */}
            <div className="space-y-6">
              <div className="bg-white dark:bg-slate-800 rounded-lg shadow-lg p-6">
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                  识别结果
                </h2>
                
                {/* 错误信息 */}
                {error && (
                  <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 mb-4">
                    <div className="flex items-center space-x-2">
                      <span className="text-red-500">❌</span>
                      <span className="text-red-700 dark:text-red-300">{error}</span>
                    </div>
                  </div>
                )}

                {/* 加载状态 */}
                {isLoading && (
                  <div className="flex items-center justify-center py-12">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
                    <span className="ml-3 text-gray-600 dark:text-gray-300">
                      正在分析音频情感...
                    </span>
                  </div>
                )}

                {/* 预测结果 */}
                {predictionResult && !isLoading && (
                  <EmotionResult result={predictionResult} />
                )}

                {/* 默认状态 */}
                {!predictionResult && !isLoading && !error && (
                  <div className="text-center py-12 text-gray-500 dark:text-gray-400">
                    <div className="text-4xl mb-4">🎵</div>
                    <p>请上传音频文件开始情感识别</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        ) : (
          // 模型管理标签页
          <div className="max-w-4xl mx-auto">
            <div className="mb-6">
              <h2 className="text-2xl font-bold text-gray-900 dark:text-white">模型管理</h2>
              <p className="text-gray-600 dark:text-gray-300 mt-1">
                管理预训练模型、训练自定义模型和切换当前使用的模型
              </p>
            </div>
            <ModelManager />
          </div>
        )}
      </main>

      {/* 页面底部 */}
      <footer className="bg-white dark:bg-slate-800 border-t border-gray-200 dark:border-slate-700 mt-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="text-center text-sm text-gray-600 dark:text-gray-300">
            <p>语音情感识别系统 v1.0.0 | 基于传统机器学习算法</p>
            <p className="mt-1">
              Copyright © 2025 彩旗工作室. All rights reserved.
            </p>
          </div>
        </div>
      </footer>
    </div>
  );
}
